package com.brian.desktools.features

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.brian.desktools.ext.isDigit
import com.brian.desktools.utils.RegexUtils
import kotlinx.coroutines.delay
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter


@Composable
fun TimeFormatScreen() {
    val (currentTime, setCurrentTime) = remember { mutableStateOf(LocalDateTime.now()) }

    val inputTime = remember { mutableStateOf("") }

    LaunchedEffect(Unit) {
        while (true) {
            delay(1000) // 每秒更新一次时间
            setCurrentTime(LocalDateTime.now())
        }
    }
    Box(Modifier.fillMaxSize().padding(horizontal = 24.dp), contentAlignment = Alignment.CenterStart) {
        Column(horizontalAlignment = Alignment.Start) {
            Row {
                Text("当前时间：")
                SelectionContainer {
                    Text(currentTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))
                }
            }

            Spacer(modifier = Modifier.height(24.dp))

            Row(verticalAlignment = Alignment.CenterVertically) {
                SelectionContainer {
                    TextField(value = inputTime.value, onValueChange = {
                        inputTime.value = it
                    })
                }
                Text("=>", modifier = Modifier.padding(horizontal = 10.dp))
                if (inputTime.value.isNotBlank()) {
                    if (RegexUtils.isValidDateTime(inputTime.value)) {
                        parseTime(inputTime.value)?.let { time ->
                            SelectionContainer {
                                Text("${time.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()}")
                            }
                        }
                    } else if (RegexUtils.matches(inputTime.value, "\\d+")) {
                        val time = LocalDateTime.ofInstant(Instant.ofEpochMilli(inputTime.value.toLong()), ZoneId.systemDefault())
                        SelectionContainer {
                            Text(time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")), modifier = Modifier)
                        }
                    }
                }
            }
        }
    }
}

private fun parseTime(input: String): LocalDateTime? {
    return try {
        LocalDateTime.parse(input, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
    } catch (e: Exception) {
        null
    }
}